package com.yinsin.security;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import com.yinsin.utils.ByteUtils;
import com.yinsin.utils.Constants;

/**
 * 3DES加解密工具
 * 
 * @author Yisin
 *
 */
public class ThreeDES {
    // 算法名称
    public static final String KEY_ALGORITHM = "desede";
    // 算法名称/加密模式/填充方式
    public static final String CIPHER_ALGORITHM = "desede/CBC/NoPadding";
    // 解释器名称
    public static String name = "DeS._.SeD._.DeS";
    public static double version = 1.001d;
    public static String info = "2016.01.01.3des";
    private static final String PUBKEY = "A85FC54753CB68765DA09D28C48651A4C54A8C5A4C1A4B1C1";
    private static final String IV = "12345678";

    public static EDProvider getEDProvider() {
        return new EDProvider(name, version, info);
    }

    /**
     * 生成密钥key对象
     * 
     * @param KeyStr
     *            密钥字符串
     * @return 密钥对象
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws Exception
     */
    private static Key keyGenerator(String keyStr) throws Exception {
        byte input[] = ByteUtils.parseHexStr2Byte(keyStr);
        DESedeKeySpec KeySpec = new DESedeKeySpec(input);
        SecretKeyFactory KeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        return ((Key) (KeyFactory.generateSecret(((java.security.spec.KeySpec) (KeySpec)))));
    }

    /**
     * CBC加密
     * 
     * @param key
     *            密钥
     * @param keyiv
     *            IV
     * @param data
     *            明文
     * @return Base64编码的密文
     * @throws Exception
     */
    public static byte[] encodeCBC(String key, byte[] keyiv, byte[] data) throws Exception {
        Security.addProvider(getEDProvider());
        Key deskey = keyGenerator(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }

    /**
     * CBC加密
     * 
     * @param key
     *            密钥
     * @param keyiv
     *            IV
     * @param data
     *            明文字符串
     * @return 密文字符串
     * @throws Exception
     */
    public static String encodeCBC(String key, String keyiv, String data) throws Exception {
        byte[] databyte = data.getBytes(Constants.CHARSET_UTF8);
        byte[] result = encodeCBC(key, keyiv.getBytes(Constants.CHARSET_UTF8), converByte(databyte));
        return ByteUtils.parseByte2HexStr(result);
    }

    /**
     * CBC加密
     * 
     * @param keyiv
     *            IV
     * @param data
     *            明文字符串
     * @return 密文字符串
     * @throws Exception
     */
    public static String encodeCBC(String keyiv, String data) throws Exception {
        return encodeCBC(PUBKEY, keyiv, data);
    }

    /**
     * CBC加密
     * 
     * @param data
     *            明文字符串
     * @return 密文字符串
     * @throws Exception
     */
    public static String encodeCBC(String data) throws Exception {
        return encodeCBC(PUBKEY, IV, data);
    }

    /**
     * CBC解密
     * 
     * @param key
     *            密钥
     * @param keyiv
     *            IV
     * @param data
     *            Base64编码的密文
     * @return 明文
     * @throws Exception
     */
    public static byte[] decodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
        Key deskey = keyGenerator(new String(key));
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }

    public static String decodeCBC(String key, String keyiv, String data) throws Exception {
        byte[] result = decodeCBC(key.getBytes(Constants.CHARSET_UTF8), keyiv.getBytes(Constants.CHARSET_UTF8), ByteUtils.parseHexStr2Byte(data));
        return new String(ByteUtils.filterByte(result), Constants.CHARSET_UTF8);
    }

    public static String decodeCBC(String keyiv, String data) throws Exception {
        return decodeCBC(PUBKEY, keyiv, data);
    }

    public static String decodeCBC(String data) throws Exception {
        return decodeCBC(PUBKEY, IV, data);
    }

    private static byte[] converByte(byte[] databyte) {
        int cl = 8 - databyte.length % 8;
        if (cl != 0) {
            int len = (int) databyte.length / 8;
            len = (databyte.length + cl);
            byte[] newbyte = new byte[len];
            for (int i = 0; i < len; i++) {
                if (i < cl) {
                    newbyte[i] = 0;
                } else {
                    newbyte[i] = databyte[i - cl];
                }
            }
            databyte = newbyte;
        }
        return databyte;
    }

}
